package com.a;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

@SuppressWarnings("unused")
public class EnvDemo {

	public static void main(String[] args) {
		//		createTempFileTest1();
		//		systemEnvsTest1();
		//		systemPropertiesTest1();
		//		jpsTest2();
		//		jpsTest1();
		//			pidTest();

	}

	private static void createTempFileTest1() {
		try {
			File tempFile1 = File.createTempFile("prefix", ".subfix");
			System.out.println(tempFile1);

			File tempFile2 = File.createTempFile("prefix", ".subfix", new File(System.getenv("HOME")));
			System.out.println(tempFile2);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void systemEnvsTest1() {
		Map<String, String> envs = System.getenv();
		for (Entry<String, String> entry : envs.entrySet()) {
			System.out.println(entry.getKey() + ":" + entry.getValue());
		}
	}

	private static void systemPropertiesTest1() {
		Properties properties = System.getProperties();
		for (Entry<Object, Object> prop : properties.entrySet()) {
			System.out.println(prop.getKey() + ":" + prop.getValue());
		}
	}

	private static void jpsTest2() {
		try {
			Process p = new ProcessBuilder("/media/dinghn/work/dinghn/software/jdk/jdk1.8.0_171/bin/jps").start();
			InputStream is = p.getInputStream();
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			copy(is, os);
			System.out.println(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void jpsTest1() {
		try {
			Process p = new ProcessBuilder("./jps").directory(new File("/media/dinghn/work/dinghn/software/jdk/jdk1.8.0_171/bin")).start();
			InputStream is = p.getInputStream();
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			copy(is, os);
			System.out.println(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void copy(InputStream is, OutputStream os) {
		try {
			byte[] buf = new byte[2048];
			int len = -1;
			while ((len = is.read(buf)) > 0) {
				os.write(buf, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void pidTest() {
		String name = ManagementFactory.getRuntimeMXBean().getName();
		System.out.println(name);
		System.out.println(name.split("@")[0]);
	}

}
